<template>
  <div class="edit">
    <a-form
      :model="formState"
      v-bind="layout"
      name="nest-messages"
      :validate-messages="validateMessages"
      @finish="onFinish"
    >
      <a-form-item
        :name="['user', 'name']"
        label="分类名称"
        :rules="[{ required: true }]"
      >
        <a-input v-model:value="formState.user.name" />

      </a-form-item>
      <a-form-item
        :name="['user', 'route']"
        label="路由描述（seo）"
      >
        <a-input v-model:value="formState.user.route" />
      </a-form-item>
      <a-form-item
        :name="['user', 'description']"
        label="描述（seo）"
      >
        <a-input v-model:value="formState.user.description" />

      </a-form-item>
      <a-form-item
        :name="['user', 'status']"
        label="状态"
      >
        <a-switch v-model:checked="formState.user.status" />
      </a-form-item>
      <a-form-item :wrapper-col="{ ...layout.wrapperCol, offset: 2 }">
        <a-button
          type="primary"
          html-type="submit"
        >{{ flag ? '添加' : '修改' }}</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import baseUrl from "@/uitils/baseUrl";
import {
  addcategories,
  getwocategories,
  editcategories,
} from "@/api/categories";
import { PlusOutlined, LoadingOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import type { UploadChangeParam, UploadProps } from "ant-design-vue";
import { reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { any } from "vue-types";
const route = useRoute();
const router = useRouter();
const flag = route.path == "/categoryCreate" ? true : false;
let id: any = null;
if (!flag) {
  id = route.params.id;
  getwocategories(id).then((res: any) => {
    formState.user = res;
  });
}
// 上传图片
function getBase64(img: Blob, callback: (base64Url: string) => void) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result as string));
  reader.readAsDataURL(img);
}
const layout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 8 },
};
const validateMessages = {
  required: "${label} is required!",
  types: {
    email: "${label} is not a valid email!",
    number: "${label} is not a valid number!",
  },
  number: {
    range: "${label} must be between ${min} and ${max}",
  },
};
const formState = reactive({
  user: {
    name: "",
    category: "",
    description: "",
    createdAt: new Date(),
    id: "",
    route: "",
    status: true,
    updatedAt: new Date(),
  },
});

const onFinish = (values: any) => {
  let obj = {
    ...values.user,
    id: "",
    route: "",
  };
  if (flag) {
    addcategories(obj).then(() => {
      message.success("添加成功");
      router.replace("/categories");
    });
  } else {
    obj.id = id;
    editcategories(obj, id).then(() => {
      message.success("添加成功");
      router.replace("/categories");
    });
  }
};
// 上传部分
const fileList = ref([]);
const loading = ref<boolean>(false);
const imageUrl = ref<string>("");
const handleChange = (info: any) => {
  if (info.file.status === "uploading") {
    loading.value = true;
    return;
  }
  if (info.file.status === "done") {
    getBase64(info.file.originFileObj, (base64Url: string) => {
      imageUrl.value = base64Url;
      loading.value = false;
    });
  }
  if (info.file.status === "error") {
    loading.value = false;
    message.error("upload error");
  }
};
const beforeUpload = (file: any) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("You can only upload JPG file!");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("Image must smaller than 2MB!");
  }
  return isJpgOrPng && isLt2M;
};
</script>

<style scoped>
.edit {
  padding-top: 20px;
}
</style>